<template>
    <div class="contain">
        <div class="cut-img">
            <img ref="imgRef" :src="img" />
            <button @click="cut">裁剪</button>
            <div v-if="state.src">
                <img style="width:200px;height:200px" :src="state.src" alt="">
            </div>
        </div>
    </div>
</template>

<script setup>
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
import { ref, nextTick, reactive } from 'vue'

const state = reactive({
    src: ''
})

const img = ref('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201811%2F07%2F20181107103350_V8nTe.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1705157920&t=cf8732aa0ced8c24189a5755d1e166c7')
const imgRef = ref()
let cropper = null
function init() {
    cropper = new Cropper(imgRef.value, {
        // 是否显示虚拟网格线
        guides: true,
        // 不允许超出图片边界
        viewMode: 1,
        // 裁剪图片的宽高比例
        aspectRatio: 1 / 1,

    });
}

function cut() {
    const data = cropper.getCroppedCanvas()
    state.src = data.toDataURL()
    console.log('查看获取到的数据信息是', state.src);
}
nextTick(() => {
    init()
})
</script>

<style lang='scss' scoped>
img {
    width: 600px;
    height: 600px;
}

.contain {
    height: 80vh;
}

.cut-img {
    width: 400px;
    height: 400px;
}
</style>